<template>
	<view class="content">
		
		<view class="cur-input">
			<view class="left">当前时间：</view>
			<view class="right">{{curTime}}</view>
			
		</view>
		<view class="btn-box" v-if="!isLogin">
			<button size="mini" type="primary" @click="goSave" class="btn">添加用户</button>
		</view>
		 <view v-if="!isLogin">
			
				<!-- <view class="quick-account">
					<view>账号选择：</view>
				    <uni-data-select
				      v-model="accountIndex"
				      :localdata="accounts"
				      @change="change"
				    ></uni-data-select>
				  </view>
		 		<uni-forms :modelValue="formData">
		 			<uni-forms-item required label="手机号" name="phone">
						<uni-easyinput type="text" v-model="formData.phone" placeholder="请输入手机号" />
		 			</uni-forms-item>
		 			<uni-forms-item required label="姓名" name="name">
		 				<uni-easyinput type="text" v-model="formData.name" placeholder="请输入姓名" />
		 			</uni-forms-item>
		 			<uni-forms-item required name="posSn" label="机身号">
		 				<uni-easyinput type="text" v-model="formData.posSn" placeholder="请输入机身号" />
		 			</uni-forms-item>
					
		 		</uni-forms>
		 		<view class="btn-box">
					<button type="primary" @click="login" v-if="!isLogin">登陆</button>
				</view> -->
				<view class="account-box">
					<view class="query-btn">
					<button type="warn" size="mini" style="width: 42%;" @click="getAccts('Y')" v-if="!isLogin">加载达标用户</button>
					<button type="info" size="mini" style="width: 42%;" @click="getAccts()" v-if="!isLogin">加载全部用户</button>
					</view>
					<view class="query-btn">
						<button size="mini" type="primary" @click="loadNum=1">已达标</button>
						<input v-model="loadSect" placeholder="500" style="width: 200upx;height: 50upx;;border:1px solid #000000;" v-if="!isRefresh"/>
						<button  size="mini" @click="sort">全部({{showAccts.length}})</button>
					</view>
					<view v-for="(item,index) in showAccts" :key="index" >
						<view class="use-account" v-if="item.num >= loadNum">
							<view class="name">{{item.name}}</view>
							<view class="money">{{item.money}}</view>
							<view class="num">{{item.num}} 次</view>
							<view class="btn-div">
								<button type="primary" size="mini" @click="preLogin(item)"  v-if="item.num > 0">开抢</button>
							</view>
						</view>
					</view>
				</view>
		 	</view>
			<view v-else class="content">
				<view class="cur-input">
					<view class="left">姓名：</view>
					<view class="right">{{customerName}}</view>
				</view>
				<view class="cur-input">
					<view class="left">客户号：</view>
					<view class="right">{{customerNo}}</view>
				</view>
				<view class="cur-input">
					<view class="left">请求频率(毫秒)：</view>
					<view class="right">
						<uni-easyinput type="text" v-model="sect" placeholder="150" />
					</view>
				</view>
				
				<view class="btn-box">
					<button type="primary" @click="start" v-if="!startBtn" class="btn">开始</button>
					<button type="warn" @click="stop" v-if="startBtn" class="btn">停止</button>
					<button  @click="logOut" v-if="!startBtn" class="btn">退出</button>
				</view>
				<view class="result">
					<uni-section title="请求结果"  type="line" padding>
						<view v-html="result" class="result-div">
						</view>
					</uni-section>
				</view>
			</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loadSect:500,
				curTime:'',
				isLogin:false,
				startBtn:false,
				sect:300,
				result:'',
				customerNo:'',
				customerName:'',
				formData:{},
				timer:'',
				accountIndex:'',
				accounts:[
				],
				accts:[
					
				],
				showAccts:[],
				loadNum:1,
				isRefresh:true
			}
		},
		onLoad() {
			this.getCurrentTime()
			// this.loadState()
			this.getAccts('Y')
		},
		methods: {
			goSave(){
				uni.navigateTo({
					url:'../saveUser/saveUser'
				})
			},
			getAccts(status){
				let that = this
				 uni.showLoading({
					title: '加载列表中...'
				});
				this.$http.post('/user/list',{status:status},res=>{
					uni.hideLoading();
					if(res.code==200){
						this.accts = res.data
						if(this.accts.length > 0){
							that.loadState()
						}
					}
				})
			},
			initData(){
				try{
					this.accts = uni.getStorageSync('ACCTS') || this.accts
					this.accounts = uni.getStorageSync('ACCOUNTS') || this.accounts
				}catch(e){
					console.log('获取缓存异常')
				}
			},
			 
			cacheAccount(){
				var isExist = false;
				for(var i=0;i<this.accts.length;i++){
					if(this.formData.phone == this.accts[i].phone){
						isExist = true;
						break;
					}
				}	
				
				if(!isExist){
					var index = this.accounts.length
					this.accounts.push({value:index,text:this.formData.name})
					this.accts.push(this.formData)
				}
				uni.setStorageSync('ACCOUNTS',this.accounts)
				uni.setStorageSync('ACCS',this.accts)
			},
			logOut(){
				clearTimeout(this.timer)
				this.stop();
				this.result=''
				this.isLogin = false
			},
			sort(){
				this.loadNum = 0
				this.showAccts.sort(function(a, b){return b.money - a.money});
			},
			sleep(delay) {
			  var start = (new Date()).getTime();
			  while ((new Date()).getTime() - start < delay) {
			    continue;
			  }
			},
			refersh(){
				window.location.reload()
			},
			async loadState(){
				this.isRefresh = true
				this.showAccts = []
				for(var i = 0;i<this.accts.length ;i++){
					let that = this
					var obj = this.accts[i]
					
					let para = {
						phone: obj.phone,
						name:  obj.name,
						posSn: obj.possn
					}
					var res = await this.$http.post('https://jinyingke.xingke.cn/opay-business/redEnvelope/check',para)
					var res = res.data
					if(res.code=='0000'){
						if(res.data){
							var item = Object.assign({},obj)
							item.customerNo = res.data.customerNo
							that.queryState(item)
						}
					}
					this.sleep(this.loadSect)
				}
				
				this.isRefresh = false
			},
			async queryState(item){
				let para = {
					customerNo:item.customerNo
				}
				para.sign = this.getSignData(para)	
				var res = await this.$http.post('https://jinyingke.xingke.cn/opay-business/redEnvelope/info',para)
				var res = res.data
				if(res.code=='0000'){
					var amount = res.data.exchangeableAmount
					var num = parseInt(amount / 80000);
					item.num = num
					item.money = parseInt(amount)
					this.updateCno(item.possn,item.customerNo,num)
					
					this.showAccts.push(item)
					this.showAccts.sort(function(a, b){return b.money - a.money});
				}
				return item.num
			},
			updateCno(posSn,cno,num){
				var status = num > 0 ?'Y':'N'
				let para = {
					posSn : posSn,
					status:status,
					cno:cno
				}
				this.$http.post('/user/edit',para,res=>{
					console.log('editUser',res)
				})
			},
			preLogin(item){
				this.customerNo = item.customerNo
				this.customerName = item.name
				this.isLogin = true;
			},
			login(){
				this.isLogin = false
				this.startBtn = false
				this.formData.sign = this.getSignData(this.formData)	
				this.$http.post('https://jinyingke.xingke.cn/opay-business/redEnvelope/check',this.formData,res =>{
					if(res.code == '0000'){
						this.customerNo = res.data.customerNo
						this.cacheAccount()
						this.isLogin = true;
					}else{
						uni.showToast({
							title:res.msg,
							icon:'error'
						})
						return
					}
				})
			},
			start(){
				this.startBtn = true
				let that = this
				let para = {
					customerNo : this.customerNo
				}
				para.sign = this.getSignData(para)
				this.$http.post('https://jinyingke.xingke.cn/opay-business/redEnvelope/extract',para,res =>{
					var flag = true
					if(res.code =='0000' && res.data){
						if(res.data.redEnvelopeAmount){
							this.result = this.curTime +": "+'【中了】：' + res.data.redEnvelopeAmount +'<br/>'
							flag = false;
							that.saveResult(that.customerNo,res.data.redEnvelopeAmount)
						}else{
							this.result = this.curTime +": "+'【Request Success】：' + res.data +'<br/>'
						}
					}else{
						this.result = this.curTime +": "+res.msg + '<br/>' + this.result
					}
					if(flag){
						this.timer = setTimeout(this.start,this.sect)
					}
				},err=>{
					// uni.showToast({
					// 	title:'频率太快了，重新开始',
					// 	icon:'error'
					// })
					this.timer = setTimeout(this.start,300)
				})
			},
			stop(){
				this.startBtn = false
				clearTimeout(this.timer)
			},
			saveResult(cno,result){
				let para = {
					cno: cno,
					result: result
				}
				this.$http.post('/result/save',para,res=>{
					console.log(res)
				})
			},
			getCurrentTime(){
				var date = new Date();
				var year = date.getFullYear();
				var  month = date.getMonth() + 1;
				var day = date.getDate();
				var hours = date.getHours();
				var minutes = date.getMinutes() < 10 ? '0'+date.getMinutes() :date.getMinutes();
				var seconds = date.getSeconds() <10 ? '0'+ date.getSeconds() : date.getSeconds();
				
				this.curTime = year + "-" + month + "-" + day + "" + "\t" + hours + ":" + minutes + ":" + seconds ;
				setTimeout(this.getCurrentTime,1000)
			},
			getSignData(para){
				var signData = this.useMd5(this.jsonToArray(para)) 
				return signData;
			},
			jsonToArray(json) {
			    var arr = [];
			    for (var i in json) {
			
			        var baseType = "";
			        var toString = "";
			
			        try {
			            baseType = JSON.parse(json[i]);
			        } catch (e) {
			            baseType = json[i];
			        }
			
					toString = '{"' + i + '":"' + json[i] + '"}';
			
			        var toJson = JSON.parse(toString);
			        arr.push(toJson);
			    }
			
			    return arr;
			},
			useMd5(array) {
			    var signKey = '86eb1492-6e08-481d-b377-678acd5c3de5';
			    var resultString = "";
			    if (array.length > 0) {
			        var parmas = [];
			        var resultArray = [];
			        for (var i = 0; i < array.length; i++) {
			            for (var key in array[i]) {
			                parmas.push(key);
			            }
			        }
			        for (var _i = 0; _i < parmas.sort(function (a, b) {
			            if (a.toString().toLowerCase() > b.toString().toLowerCase()) {
			                return 1;
			            } else {
			                return -1;
			            }
			        }).length; _i++) {
			            for (var j = 0; j < array.length; j++) {
			                for (var _key in array[j]) {
			                    if (parmas[_i] == _key) {
			                        if (Array.isArray(array[j][_key])) {
			                            array[j][_key] = JSON.stringify(array[j][_key]);
			                        }
			                        resultArray.push(array[j]);
			                    }
			                }
			            }
			        }
			
			        resultArray.map(function (el, index) {
			            for (var _key2 in el) {
			                resultString += _key2 + "=" + el[_key2];
			            }
			        });
			    }
			    return this.$md5.hex_md5_32(resultString + signKey);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.quick-account{
		display: flex;
		align-items: center;
		height: 60upx;
		margin-bottom: 5px;
	}
	.cur-time{
		width: 700upx;
		height: 60upx;
		line-height: 60upx;
		margin-bottom: 3px; 
		display: flex;
		flex-wrap: nowrap;
	}
	.content {
		width: 750upx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.cur-input{
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 36px;
		.left{
			width: 250upx;
			text-align: right;
		}
		.right{
			width: 350upx;
		}
	}
	 .btn-box{
		 margin-top: 20upx;
		 display: flex;
		 justify-content: space-between;
		 width: 690upx;
		 .btn{
			 width: 240upx;
			 border-radius: 50upx;
		 }
	 }
	 .result{
		 width: 750upx;
		 text-align: left;
	 }
	 .result-div{
		 width: 100%;
		 height: 900upx;
		 overflow: hidden;
	 }
	 .account-box{
		 border: 1px solid #e2e2e2;
		 width: 690upx;
		 height: 1600upx;
		 overflow: auto;
		 padding: 20upx;
	 }
	 .use-account{
		 display: flex;
		 justify-content: space-between;
		 align-items: center;
		 height: 70upx;
		 line-height: 70upx;
		 border-bottom: 1px solid #e2e2e2;
		 margin-top: 20upx;
		 .name{
			 width: 100upx;
		 }
		 .money{
			 width: 150upx;
			 text-align: right;
		 }
		 .num{
			 width: 100upx;
			 text-align: center;
		 }
		 .btn-div{
			 width: 200upx;
			 display: flex;
			 align-items: center;
			 .btn{
				 width:120upx;
				 height:50upx;
				 font-size: 24upx;
				 border-radius: 20upx;
				 background-color: #000000!important;
			 }
		 }
	 }
	 .query-btn{
		 display: flex;
		 justify-content: space-around;
		 align-items: center;
		 margin-bottom: 30upx;
		 padding-bottom: 20upx;
		 border-bottom: 1px solid #e2e2e2;
		 
	 }
</style>
